package com.md.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.md.api.common.utils.AESUtil;
import com.md.api.common.utils.StringUtils;
import com.md.api.common.utils.TokenUtil;
import com.md.api.common.utils.UrlUtil;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.dto.ComposeCommitDto;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.util.Page;
import com.md.api.service.ShareSevice;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.UrlBase64Encoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author liujie
 * @ClassName PhotoServiceImpl
 **/

@Slf4j
@Service
public class ShareServiceImpl implements ShareSevice {

    @Resource
    TokenUtil tokenUtil;
    @Resource
    PhotoInfoMapper photoMapper;
    @Resource
    PictureInfoMapper pictureMapper;
    @Resource
    ShareRecordMapper shareRecordMapper;
    @Resource
    VisitRecordMapper visitRecordMapper;
    @Resource
    TbOrderVirtuallyMapper virtuallyMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    UserVipMapper userVipMapper;
    @Value("${common-key}")
    String commonKey;

    @Override
    public HttpResult pictureList(HttpServletRequest request, ComposeQueryDto qto) {
        String language = request.getHeader("language");
        String userId = tokenUtil.getUserId(request);
        ShareRecord byShareId = shareRecordMapper.getByShareId(qto.getShareId());
        if(!byShareId.getShareUserId().equals(userId)) {
            if (StringUtils.isNotEmpty(byShareId.getSecret())) {
                if (StringUtils.isEmpty(qto.getSecret())){
                    return HttpResult.SECRET_VISIT;
                }
                int i = shareRecordMapper.checkSecret(qto.getShareId(), qto.getSecret());
                if (i == 0) {
                    if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                        return HttpResult.fail("Password error");
                    }
                    return HttpResult.fail("密碼錯誤！");
                }
            }
        }
        if (byShareId.getShareType()!=1){
            if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                return HttpResult.fail("The sharing type is not an album");
            }
            return HttpResult.fail("分享類型不是相冊！");
        }
        List<PictureInfo> list = pictureMapper.getByPhotoId(byShareId.getSthIds(),null,qto.getCherryPick());
        return new HttpResult(list);
    }

    @Override
    public HttpResult visitRecord(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(VisitRecord.class);
        String userId = tokenUtil.getUserId(request);
        List<VisitRecord> list = visitRecordMapper.getByUserId(userId);
        for (VisitRecord vr :list){
            if (vr.getShareType()==1){
                PhotoInfo byPhotoId = photoMapper.getByPhotoId(vr.getSthIds());
                vr.setCoverImageUrl(byPhotoId.getCoverImageUrl());
                vr.setPhotoName(byPhotoId.getPhotoName());
                vr.setBeginDate(byPhotoId.getBeginDate());
                vr.setValidDate(byPhotoId.getValidDate());
            }
        }
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult shareDeail(HttpServletRequest request, ComposeQueryDto qto) {
        String language = request.getHeader("language");
        ShareRecord byShareId = shareRecordMapper.getByShareId(qto.getShareId());
        if (null==byShareId){
            if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                return HttpResult.fail("No share record!");
            }
            return HttpResult.fail("暫無分享記錄！");
        }
        boolean hasVisited = false;
        String userId = tokenUtil.getUserId(request);
        //记录访问记录
        if (StringUtils.isNotEmpty(userId)) {
            VisitRecord byUserIdAndShareId = visitRecordMapper.getByUserIdAndShareId(userId, qto.getShareId());
            if (null == byUserIdAndShareId) {
                VisitRecord vr = new VisitRecord();
                vr.setShareId(qto.getShareId());
                vr.setVisitUserId(userId);
                visitRecordMapper.insert(vr);
            }else{
                hasVisited = true;
            }
        }

        if (!hasVisited&&StringUtils.isNotEmpty(byShareId.getSecret())) {
            if (StringUtils.isEmpty(qto.getSecret())){
                return HttpResult.SECRET_VISIT;
            }
            int i = shareRecordMapper.checkSecret(qto.getShareId(), qto.getSecret());
            if (i == 0) {
                if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                    return HttpResult.fail("Password error");
                }
                return HttpResult.fail("密碼錯誤！");
            }
        }
        if(!byShareId.getShareUserId().equals(userId)||StringUtils.isEmpty(userId)) {
            shareRecordMapper.plusVisitCount(qto.getShareId());
        }
        Map<String,Object> resultMap = new HashMap<>();
        UserInfo user = userMapper.getBaseInfoByUserId(byShareId.getShareUserId());
        resultMap.put("user",user);
        if (byShareId.getShareType()==1){
            PhotoInfo dbPhoto = photoMapper.getByPhotoId(byShareId.getSthIds());
            resultMap.put("photo",dbPhoto);
            return new HttpResult(resultMap);
        }else if(byShareId.getShareType()==2){
            List<PictureInfo> list = new ArrayList<>();
            for (String pictureId: StringUtils.toList(byShareId.getSthIds())){
                PictureInfo picture = pictureMapper.getByPictureId(pictureId);
                list.add(picture);
            }
            resultMap.put("picture",list);
            return new HttpResult(resultMap);
        }
        return HttpResult.fail("暫無相關記錄！");
    }


    @Override
    public HttpResult shareCoverImg(HttpServletRequest request, ComposeQueryDto qto) {
        String language = request.getHeader("language");
        ShareRecord byShareId = shareRecordMapper.getByShareId(qto.getShareId());
        if (null==byShareId){
            if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                return HttpResult.fail("No share record!");
            }
            return HttpResult.fail("暫無分享記錄！");
        }
        PhotoInfo dbPhoto = null;
        if (byShareId.getShareType()==1){
            dbPhoto = photoMapper.getByPhotoId(byShareId.getSthIds());

        }else if(byShareId.getShareType()==2){
            List<String> pictureIds = StringUtils.toList(byShareId.getSthIds());
            PictureInfo picture = pictureMapper.getByPictureId(pictureIds.get(0));
            dbPhoto = photoMapper.getByPhotoId(picture.getPhotoId());
        }
        return new HttpResult(dbPhoto.getCoverImageUrl());
    }

    @Override
    public HttpResult saveShare(HttpServletRequest request, ShareRecord shareRecord)  {
        String userId = tokenUtil.getUserId(request);
        shareRecord.setShareUserId(userId);
        String shareId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        shareRecord.setShareId(shareId);
        JSONObject reqMap = new JSONObject();
        reqMap.put("shareId",shareId);
        reqMap.put("shareType",shareRecord.getShareType());
        reqMap.put("visitType","custom");
//        PhotoInfo dbPhoto = photoMapper.getByPhotoId(shareRecord.getSthIds());
//        if (null!=dbPhoto&&StringUtils.isNotEmpty(dbPhoto.getCoverImageUrl())) {
//            reqMap.put("coverImageUrl", dbPhoto.getCoverImageUrl());
//        }
        Map<String,String> resultMap = new HashMap();
        try {
            String customGetParam = URLEncoder.encode(AESUtil.encrypt(UrlUtil.jsonToGet(reqMap.toJSONString()),commonKey),"UTF-8");
            reqMap.put("visitType","sponsor");
            String sponsorGetParam = URLEncoder.encode(AESUtil.encrypt(UrlUtil.jsonToGet(reqMap.toJSONString()),commonKey),"UTF-8");
            String customUrl = shareRecord.getHtmlUrl()+"?"+customGetParam;
            String sponsorUrl = shareRecord.getHtmlUrl()+"?"+sponsorGetParam;
            shareRecord.setShareUrl(customUrl+";"+sponsorUrl);
            shareRecordMapper.saveShare(shareRecord);

            resultMap.put("custom",customUrl);
            resultMap.put("sponsor",sponsorUrl);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new HttpResult(resultMap);
    }

    @Override
    public HttpResult checkSecret(HttpServletRequest request, ShareRecord shareRecord) {
        int i = shareRecordMapper.checkSecret(shareRecord.getShareId(),shareRecord.getSecret());
        if (i>0){
            return HttpResult.OK;
        }
        return HttpResult.fail("密碼錯誤！");
    }


    @Override
    public HttpResult subAItimes(HttpServletRequest request, String shareId) {
        String language = request.getHeader("language");
        ShareRecord byShareId = shareRecordMapper.getByShareId(shareId);
        UserInfo user = userMapper.getBaseInfoByUserId(byShareId.getShareUserId());
        Integer totalEffectiveAITimes = virtuallyMapper.getTotalEffectiveAITimes(byShareId.getShareUserId());
        if (null == totalEffectiveAITimes) {
            if (StringUtils.isNotEmpty(language) && language.equals("en")) {
                return HttpResult.fail("Insufficient AI usage, please upgrade membership or purchase AI usage");
            }
            return HttpResult.fail("AI次數不足，請升級會員或購買AI次數！");
        }
        if (user.getUseAiTimes() >= totalEffectiveAITimes) {
            if (StringUtils.isNotEmpty(language) && language.equals("en")) {
                return HttpResult.fail("Insufficient AI usage, please upgrade membership or purchase AI usage");
            }
            return HttpResult.fail("AI次數不足，請升級會員或購買AI次數！");
        }
        user.setUseAiTimes(user.getUseAiTimes()+1);
        userMapper.updateAiTimes(user);
        return HttpResult.OK;
    }

    @Override
    public HttpResult subFaceTimes(HttpServletRequest request, String shareId) {
        String language = request.getHeader("language");
        ShareRecord byShareId = shareRecordMapper.getByShareId(shareId);
        UserInfo user = userMapper.getBaseInfoByUserId(byShareId.getShareUserId());
        Integer totalEffectiveFaceTimes = virtuallyMapper.getTotalEffectiveFaceTimes(byShareId.getShareUserId());
        if (null == totalEffectiveFaceTimes) {
            if (StringUtils.isNotEmpty(language) && language.equals("en")) {
                return HttpResult.fail("Insufficient facial scanning and photo taking times, please upgrade to a member or purchase facial scanning times");
            }
            return HttpResult.fail("掃臉取相次數不足，請升級會員或購買掃臉次數！");
        }
        if (user.getUseFaceTimes() >= totalEffectiveFaceTimes) {
            if (StringUtils.isNotEmpty(language) && language.equals("en")) {
                return HttpResult.fail("Insufficient facial scanning and photo taking times, please upgrade to a member or purchase facial scanning times");
            }
            return HttpResult.fail("掃臉取相次數不足，請升級會員或購買掃臉次數！");
        }
        user.setUseFaceTimes(user.getUseFaceTimes()+1);
        userMapper.updateFaceTimes(user);
        return HttpResult.OK;
    }

    public static void main(String[] args) {

        System.out.println(AESUtil.decrypt("9yBV+NeqSHtB9JRJCWFZiW5nIYbb1EFziVmVBT7iCfeFyPRTnil3iNMck/y/yOpn2Xj+qB2QhadH6LcwDaqu6r82iU2zJz+CX8L90kONQ+w=","7c24mhsuqzrgssb5"));


    }
}
